package com.qos.fun;

import android.app.Activity;
import android.app.Fragment;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class QueueActivity extends Activity {
	private static final String LOG="queueact";  

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(LOG, "Activity on Create");
    }
    
    public static class QueueFragment extends Fragment {
        
        View v;
        Button bt1;
        TextView tv1,tv2,tv3;
        
        Messenger mMessenger = null;
        /** Messenger for communicating with service. */
        Messenger mService = null;
        /** Flag indicating whether we have called bind on the service. */
        boolean mIsBound;
        
        /**
         * Class for interacting with the main interface of the service.
         */
        private ServiceConnection mConnection = new ServiceConnection() {
            public void onServiceConnected(ComponentName className,
                    IBinder service) {
                // This is called when the connection with the service has been
                // established, giving us the service object we can use to
                // interact with the service.  We are communicating with our
                // service through an IDL interface, so get a client-side
                // representation of that from the raw service object.
                mService = new Messenger(service);
                try {
                    Message msg = Message.obtain(null,ConnectManager.MSG_QUEUE_QUERY);
                    msg.replyTo = mMessenger;
                    mService.send(msg);
                    
                } catch (RemoteException e) {
                    // In this case the service has crashed before we could even
                    // do anything with it; we can count on soon being
                    // disconnected (and then reconnected if it can be restarted)
                    // so there is no need to do anything here.
                }
            }

            public void onServiceDisconnected(ComponentName className) {
                // This is called when the connection with the service has been
                // unexpectedly disconnected -- that is, its process crashed.
                mService = null;

            }
        };
        
        void doBindService() {
            // Establish a connection with the service.  We use an explicit
            // class name because there is no reason to be able to let other
            // applications replace our component.
            getActivity().bindService(new Intent(getActivity(), 
                    ConnectManager.class), mConnection, Context.BIND_AUTO_CREATE);
            mIsBound = true;
        }
        
        void doUnbindService() {
            if (mIsBound) {
                
                // Detach our existing connection.
                getActivity().unbindService(mConnection);
                mIsBound = false;
            }
        }
        
        public class IncomingHandler extends Handler {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case ConnectManager.MSG_QUEUE_QUERY:
                        /**
                         * TODO bug prone
                         */
                        Log.d(LOG, "query return is "+msg.arg1);
                        Bundle data = msg.getData();
                        setQueryResult(String.valueOf(msg.arg1));
                        setQueryStart(data.getString("queuestartflag"));
                       
                        break;
                    default:
                        super.handleMessage(msg);
                }
            }
        }

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setHasOptionsMenu(true);
            mMessenger = new Messenger(new IncomingHandler());
            doBindService();
        }

        @Override
        public void onCreateOptionsMenu(Menu menu,MenuInflater inflater) {
            inflater.inflate(R.menu.activity_queue, menu);
            super.onCreateOptionsMenu(menu, inflater);
        }
        
        @Override
        public boolean onOptionsItemSelected(MenuItem item){
            switch(item.getItemId()) {
                case R.id.queue_add:
                    Log.d(LOG, "add queue");
                    Toast.makeText(getActivity(), "add queue!", Toast.LENGTH_SHORT).show();
                    break;
                    
                default:
                    break;
                    }
            return true;
        }

        /**
         * The Fragment's UI is just a simple text view showing its
         * instance number.
         */
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            Log.d(LOG, "fragment on Create view");
            v =  inflater.inflate(R.layout.activity_queue, container, false);
            tv1 = (TextView)v.findViewById(R.id.queryerr);
            tv2 = (TextView)v.findViewById(R.id.queuestart);
            
            tv3 = (TextView)v.findViewById(R.id.ordernum);
            
            bt1 = (Button)v.findViewById(R.id.requestQueue);
            bt1.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    Log.d(LOG, "on click");
                    
                    // We want to monitor the service for as long as we are
                    // connected to it.
                    try {
                        Message msg = Message.obtain(null,ConnectManager.MSG_QUEUE_ORDER);
                        /** FIXME: need to set restaurant ID
                         * 
                        Bundle data = new Bundle();
                        data.putInt("restaurantid", 1);
                        msg.setData(data);
                        */
                        msg.replyTo = mMessenger;
                        mService.send(msg);
                        
                    } catch (RemoteException e) {
                        // In this case the service has crashed before we could even
                        // do anything with it; we can count on soon being
                        // disconnected (and then reconnected if it can be restarted)
                        // so there is no need to do anything here.
                    }
                }

            });
            return v;
        }
        
        public void setQueryResult(String param) {
            tv1.setText(param);
        }
        
        public void setQueryStart(String param) {
            tv2.setText(param);
        }
        @Override
        public void onDestroy() {
            super.onDestroy();
            
            doUnbindService();
        }

    }
}
